#!/usr/bin/env node
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const fs = require('fs-extra');
const replace = require('replace');

if (process.argv.length !== 5) {
  console.log('Usage: mv <src-location> <old-component-name> <new-component-name>');
  process.exit();
}

const location = process.argv[2];
const oldName = process.argv[3];
const newName = process.argv[4];

if (!/^([a-z0-9-])+$/.test(oldName)) {
  console.log('must be a hyphen case old name');
  process.exit();
}

if (!/^([a-z0-9-])+$/.test(newName)) {
  console.log('must be a hyphen case new name');
  process.exit();
}

const oldPath = './src/' + location + '/' + oldName + '/';
const newPath = './src/' + location + '/' + newName + '/';

const camelOldName = oldName.replace(/(^|-)[a-z]/g, s => s.replace('-', '').toUpperCase());
const camelNewName = newName.replace(/(^|-)[a-z]/g, s => s.replace('-', '').toUpperCase());

console.log('Making path:', newPath);

fs.moveSync(oldPath, newPath);
fs.renameSync(newPath + oldName + '.tsx', newPath + newName + '.tsx');
try {
  fs.renameSync(newPath + oldName + '.scss', newPath + newName + '.scss');
} catch {}
try {
  fs.renameSync(newPath + oldName + '.spec.tsx', newPath + newName + '.spec.tsx');
} catch {}

const replacePath = './src/';

replace({
  regex: oldName,
  replacement: newName,
  paths: [replacePath],
  recursive: true,
  silent: true,
});

replace({
  regex: camelOldName,
  replacement: camelNewName,
  paths: [replacePath],
  recursive: true,
  silent: true,
});
